<template>
  <sys-layout class="sys-page">
    <template v-slot:top>
      <slot name="top">
        <sys-query v-if="showQuery" ref="query" :model="model" :labelWidth="labelWidth" @query="handleQuery" v-bind="queryProps" v-on="$listeners">
          <template slot="action">
            <slot name="query_action"></slot>
          </template>
          <template slot="actionAppend">
            <slot name="actionAppend"></slot>
          </template>
          <slot name="form"></slot>
          <template slot="form-adv">
            <slot name="form-adv"></slot>
          </template>
          <template slot="toolBar">
            <slot name="toolBar"></slot>
          </template>
        </sys-query>
        <div class="sys-page-tool">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="$emit('add')" v-if="showAddBtn">新增</el-button>
          <slot name="tools"></slot>
        </div>
      </slot>
    </template>

    <my-table ref="table"
              size="small"
              :fit="fit"
              border
              :columns="columns"
              @select-all="onSelectAll"
              @select="onSelect"
              :loader="loadFn"
              :pageSize="pageSize"
              :pagination="pagination"
              :toolbar="toolbar || selectedAble"
              v-bind="tableProps"
              v-on="tableListeners"
    >
      <!-- my-table的slots -->

      <template>
        <template slot="title">
          <slot name="table-title"></slot>

          <!-- 可以选择时现实 -->
          <slot name="table-selected">
            <el-badge v-if="selectedAble" :value="shopList.length">
              <el-button size="small" v-popover:popover>已选择</el-button>
            </el-badge>
          </slot>

        </template>
        <template slot="actions">
          <slot name="table-actions"></slot>
        </template>
      </template>

      <!-- element-table 列的插槽 -->
      <template v-for="(col) in columns" slot-scope="prop" :slot="col.prop" v-if="col.prop">
        <slot :name="col.prop" v-bind="prop">
          {{prop.row[col.prop]}}
        </slot>
      </template>
    </my-table>

    <!-- 弹窗 -->
    <simple-dialog v-bind.sync="dialog" @on-ok="onDialogOk"/>

    <template v-slot:footer>
      <slot name="footer"></slot>
    </template>

    <slot></slot>

    <el-popover
      ref="popover"
      trigger="click"
      placement="right"
      :popper-class="popperClass"
    >
      <div class="sys-page-popover">
        <my-table border fit :columns="currSelectedColumns" :data="shopList" size="mini">
          <template v-slot:ctrl="{row, $index}">
            <el-button type="text" icon="el-icon-delete" @click="onRemove(row, $index)">移除</el-button>
          </template>
        </my-table>
      </div>
    </el-popover>
  </sys-layout>
</template>

<script>
import sysLayout from './sys-layout'
import sysQuery from './sys-query2'
import simpleDialog from '../dialog/simple-dialog'
// 分页
import sysPageSelectMixin from './sys-page-select-mixin'
/**
 * 插槽
 * @member slots
 * @property {string} top 顶部布局
 * @property {string} form 查询表单
 * @property {string} table-title 表格标题
 * @property {string} table-actions 表格action
 * @property {string} table-toolbar 表格-工具栏
 * @property {string} footer 底部布局
 */
export default {
  name: 'sys-page',
  cnName: '列表-展示页',
  mixins: [sysPageSelectMixin],
  components: {
    sysLayout,
    sysQuery,
    simpleDialog
  },
  /**
   * 属性参数
   * @member props
   * @property {Boolean} [model] fit，是否高度百分百
   * @property {Object} [model] 表单model
   * @property {String} [labelWidth] 表单labelWidth
   * @property {Function} [showQuery] 是否显示查询
   * @property {Function} [beforeQuery] 查询前事件
   * @property {Object} [queryProps] sysQuery的props
   * @property {Array} [columns] 表格列
   * @property {Function} [loader] 表格请求函数
   * @property {Boolean} [selectedAble] 默认false，如果为true，则提供分页选择功能
   * @property {Boolean} [toolbar] 默认false，对应my-table的toolbar
   * @property {String} [popperClass] 选中数据popper样式类
   * @property {Array} [selectedColumnsRange] 默认[1,3],从columns中截取处对应下表列做选中展示列。会从columns中获取前若干位当做列展示
   * @property {Array} [selectedColumns] 选中表格展示列（优先级高于selectedColumnsNum）
   * @property {Number} [pageSize] 默认页大小
   * @property {Array} [pagination] 分页其他配置
   */
  props: {
    fit: {
      type: Boolean,
      default: true
    },
    model: Object,
    labelWidth: String,
    showQuery: {
      type: Boolean,
      default: true
    },
    beforeQuery: Function,
    queryProps: {
      type: Object
    },
    columns: Array,
    loader: {
      type: Function,
      required: true
    },
    selectedAble: {
      type: Boolean,
      default: false
    },
    toolbar: {
      type: Boolean,
      default: false
    },
    popperClass: String,
    selectedColumnsRange: {
      type: Array,
      default() {
        return [1, 3]
      }
    },
    selectedColumns: {
      type: Array,
      default: null
    },
    tableProps: {
      type: Object
    },
    tableListeners: {
      type: Object
    },
    pageSize: {
      type: Number,
      default: 10
    },
    pagination: {
      type: Object,
      default() {
        return {
          background: true,
          layout: 'total, sizes, ->, prev, pager, next'
        }
      }
    },
    showAddBtn: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialog: {
        title: '',
        visible: false,
        comp: null,
        width: '60%',
        height: '50%',
        props: {}
      }
    }
  },
  methods: {
    reload() {
      this.$refs.table && this.$refs.table.load()
    },
    handleQuery(model) {
      this.$emit('query', model)
      if (this.beforeQuery) {
        this.beforeQuery(model).then(_ => {
          this.reload()
        })
      } else {
        this.reload()
      }

    },
    async loadFn(page, pageSize) {
      const model = this.model
      const res = await this.loader({...model, page, limit: pageSize})
      if(res.page) {
        res.page.total = res.page.totalCount || res.page.total
        return res.page
      } else {
        res.total = res.totalCount || res.total
      }
      if(this.primaryField) {
        this.$nextTick(_ => {
          setTimeout(_ => {
            this.setDataChecked(res.list)
          }, 100)
        })
      }
      return res
    },
    setDialog(options) {
      options.visible = true
      this.dialog = Object.assign({}, this.dialog, options)
    },
    onDialogOk(data) {
      this.dialog.visible = false
      this.$emit('dialog-ok')
      this.reload()
    },
    onSelectAll(selection) {
      if(!this.selectedAble) {
        this.$emit('select-all', selection)
        return
      }
      this.doSelectAll(selection)
    },
    onSelect(selection) {
      if(!this.selectedAble) {
        this.$emit('select', selection)
        return
      }
      this.doSelect(selection)
    }
  },
  watch: {},
  computed: {
    $table() {
      // 获取el-table，因为切换选择框时候需要
      return this.$refs.table.$refs.elTable
    },
    currSelectedColumns() {
      if(this.selectedColumns) {
        return this.selectedColumns
      }
      const start = this.selectedColumnsRange[0]
      const end = this.selectedColumnsRange[1]
      const columns = this.columns.slice(start, end)
      columns.push({
        prop: 'ctrl',
        label: '操作',
        align: 'center'
      })
      return columns
    }
  },
  mounted() {

  }
}
</script>

<style lang="scss" scoped>
.sys-page {
  padding: 0;
  border: 5px solid #f0f0f0;

  &-tool {
    padding: 8px;
  }

  &-popover {
    min-width: 400px;
    max-height: 400px;
    overflow: auto;
  }

}
</style>
